<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <div class="header-title">
        <h1>智能考勤系统 - 数据总览</h1>
      </div>
    </div>
    <div class="card-container" v-loading="loading">
      <!-- 总体出勤情况统计卡片 -->
      <div class="summary-card">
        <div class="card-header">
          <h2>总体出勤情况</h2>
          <span class="update-time">更新时间：{{ formattedTime }}</span>
        </div>
        <div class="summary-content">
          <div class="chart-container" id="summary-chart"></div>
          <div class="summary-stats">
            <div class="stat-item present">
              <div class="stat-icon"><i class="el-icon-user"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ totalPresent }}<span class="percent-sign"></span></div>
                <div class="stat-label">总出勤人次</div>
              </div>
            </div>
            <div class="stat-item absent">
              <div class="stat-icon"><i class="el-icon-user-solid"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ totalAbsent }}<span class="percent-sign"></span></div>
                <div class="stat-label">总缺勤人次</div>
              </div>
            </div>
            <div class="stat-item rate">
              <div class="stat-icon"><i class="el-icon-data-analysis"></i></div>
              <div class="stat-details">
                <div class="stat-value">{{ attendanceRate }}<span class="percent-sign">%</span></div>
                <div class="stat-label">总出勤率</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 学生成绩排名卡片 -->
      <div class="top-students-card">
        <div class="card-header">
          <h2>学生成绩排名</h2>
          <div class="header-actions">
            <el-select v-model="rankLimit" size="mini" placeholder="选择显示数量" @change="fetchTopStudents">
              <el-option :value="3" label="Top 3"></el-option>
              <el-option :value="5" label="Top 5"></el-option>
              <el-option :value="10" label="Top 10"></el-option>
            </el-select>
          </div>
        </div>
        <div class="students-content" >
          <template v-if="topStudents.length > 0">
            <el-table
              :data="topStudents"
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa' }"
              :cell-style="{ padding: '8px 0' }">
              <el-table-column type="index" label="排名" width="80" align="center">
                <template slot-scope="scope">
                  <div class="rank-badge-container">
                    <div :class="['rank-badge', getRankClass(scope.$index)]">{{ scope.$index + 1 }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="studentName" label="姓名" min-width="100"></el-table-column>
              <el-table-column prop="classId" label="班级" min-width="100"></el-table-column>
              <el-table-column prop="courseName" label="主修课程" min-width="120"></el-table-column>
              <el-table-column prop="totalScore" label="总成绩" width="100" sortable>
                <template slot-scope="scope">
                  <span class="score-value">{{ scope.row.totalScore }}</span>
                </template>
              </el-table-column>
              <el-table-column label="出勤率" min-width="180">
                <template slot-scope="scope">
                  <div class="attendance-rate-container">
                    <el-progress 
                      :percentage="scope.row.attendanceRate" 
                      :color="getAttendanceRateColor(scope.row.attendanceRate)"
                      :format="percentFormat"
                      :stroke-width="8">
                    </el-progress>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <div class="no-data" v-else>
            <i class="el-icon-warning"></i>
            <span>暂无学生成绩数据</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'AttendanceSummary',
  data() {
    return {

      totalPresent: 0,
      totalAbsent: 0,
      attendanceRate: 0,
      lastUpdated: new Date(),
      loading: false,
      chart: null,
      // 学生排名相关
      rankLimit: 3,
      topStudents: [],
    };
  },
  mounted() {
    this.fetchData();
    this.fetchTopStudents();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  computed: {
    formattedTime() {
      const date = new Date(this.lastUpdated);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  },

  methods: {
    async fetchData() {

        const response = await this.$request.get('/attendance/summary');
        this.totalPresent = response.presentCount || 0
        this.totalAbsent = response.absentCount || 0
        this.attendanceRate = response.attendanceRate || 0
        this.lastUpdated = response.lastUpdated ? new Date(response.lastUpdated) : new Date()
        this.initChart();
    },
    
    async fetchTopStudents() {
        const response = await this.$request.get(`/students/topscores?limit=${this.rankLimit}`);
          this.topStudents = response;
    },
    
    initChart() {
      const chartDom = document.getElementById('summary-chart');
      if (!chartDom) return;
      
      if (this.chart) {
        this.chart.dispose();
      }
      
      this.chart = echarts.init(chartDom);
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: ['出勤', '缺勤']
        },
        color: ['#67C23A', '#F56C6C'],
        series: [
          {
            name: '出勤情况',
            type: 'pie',
            radius: ['55%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: () => {
                return `出勤率\n${this.attendanceRate}%`;
              },
              fontSize: 16,
              fontWeight: 'bold'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.totalPresent, name: '出勤' },
              { value: this.totalAbsent, name: '缺勤' }
            ]
          }
        ]
      };
      
      this.chart.setOption(option);
    },
    
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    
    getRankClass(index) {
      if (index === 0) return 'gold';
      if (index === 1) return 'silver';
      if (index === 2) return 'bronze';
      return '';
    },
    
    getAttendanceRateColor(rate) {
      if (rate >= 90) return '#67C23A';
      if (rate >= 75) return '#E6A23C';
      return '#F56C6C';
    },
    
    percentFormat(percentage) {
      return percentage + '%';
    }
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  /* 将背景颜色从浅灰色 #f5f7fa 修改为纯白色 #ffffff */
  background-color: #ffffff;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  /* 这个边框颜色是 #e6e6e6 (浅灰色)，如果觉得有问题也可以修改 */
  border-bottom: 1px solid #e6e6e6;
}

.header-title h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.date-display, .user-display {
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 5px;
}

.date-display i, .user-display i {
  font-size: 16px;
  color: #409EFF;
}

.card-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-card, .top-students-card {
  background-color: white; /* 卡片背景色是白色 */
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
  height: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  /* 这个边框颜色是 #f2f2f2 (非常浅的灰色)，如果觉得有问题也可以修改 */
  border-bottom: 1px solid #f2f2f2;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.update-time {
  font-size: 12px;
  color: #909399;
}

.header-actions {
  display: flex;
  align-items: center;
}

.summary-content {
  display: flex;
  height: 260px;
}

.chart-container {
  height: 100%;
  flex: 1;
}

.summary-stats {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 10px;
  width: 35%;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 6px;
  color: white;
  gap: 12px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
  overflow: hidden;
}

.stat-item:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0) 60%);
  pointer-events: none;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.stat-item.present {
  background-color: #67C23A;
}

.stat-item.absent {
  background-color: #F56C6C;
}

.stat-item.rate {
  background-color: #409EFF;
}

.stat-icon {
  font-size: 20px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  min-width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.stat-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 0.5px;
  line-height: 1;
  display: flex;
  align-items: baseline;
  font-family: "Arial", "PingFang SC", "Hiragino Sans GB", sans-serif;
  margin-bottom: 4px;
}

.percent-sign {
  font-size: 16px;
  font-weight: normal;
  margin-left: 2px;
}

.stat-label {
  font-size: 13px;
  opacity: 0.9;
  font-weight: 500;
}

.students-content {
  min-height: 300px;
}

.rank-badge-container {
  display: flex;
  justify-content: center;
}

.rank-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  font-weight: bold;
  color: white;
  background-color: #909399;
}

.rank-badge.gold {
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  box-shadow: 0 2px 6px rgba(255, 215, 0, 0.3);
}

.rank-badge.silver {
  background: linear-gradient(135deg, #E0E0E0 0%, #B0B0B0 100%);
  box-shadow: 0 2px 6px rgba(176, 176, 176, 0.3);
}

.rank-badge.bronze {
  background: linear-gradient(135deg, #CD7F32 0%, #A05215 100%);
  box-shadow: 0 2px 6px rgba(205, 127, 50, 0.3);
}

.attendance-rate-container {
  padding: 0 10px;
}

.score-value {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.no-data {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
  gap: 10px;
}

.no-data i {
  font-size: 48px;
}

#summary-chart {
  width: 65%;
}

@media (max-width: 768px) {
  .summary-card, .top-students-card {
    height: auto;
  }

  .summary-content {
    flex-direction: column;
    height: auto;
  }

  #summary-chart {
    width: 100%;
    height: 250px;
    margin-bottom: 20px;
  }

  .summary-stats {
    width: 100%;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-info {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  .stat-card {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }
  .stat-icon {
    margin-bottom: 10px;
  }
}
</style>